package com.fxb.service_control.context;

import java.util.List;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.eureka.CloudEurekaClient;
import org.springframework.cloud.netflix.eureka.InstanceInfoFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;

import lombok.extern.slf4j.Slf4j;

/**
 * @author wangxiyue
 * @date 2021-01-21 13:00
 * @since 1.0.0
 */
@Component
@Slf4j
public class ServiceContextHolder implements ApplicationContextAware {

    private DiscoveryClient discoveryClient;

    public static final Map<String, ServiceInstance> instanceId2Instances = Maps.newHashMapWithExpectedSize(1024);

    public static final Map<String, List<ServiceInstance>> serviceId2ServiceInstanceMaps = Maps.newHashMapWithExpectedSize(
            1024);

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        List<String> services = discoveryClient.getServices();
        services.forEach(serviceId -> {
            List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
            // 不用toLowCase(),discoveryClient.getServices()中已经返回了小写的name
            serviceId2ServiceInstanceMaps.put(serviceId, instances);
            instances.forEach(instance -> {
                log.debug("<获取到服务实例> instance=[{}]", instance);
                instanceId2Instances.put(instance.getInstanceId().toLowerCase(), instance);
            });
        });
    }

    @Autowired
    public void setDiscoveryClient(DiscoveryClient discoveryClient) {
        this.discoveryClient = discoveryClient;
    }


}
